package com.beaven.model.data.user;

import com.beaven.model.Factory;
import com.beaven.model.data.DataSource;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.card.CategoryCard;
import com.beaven.model.model.db.Category;
import java.util.List;
import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/5/27 17:08
 */

public class CategoryPresenter
    implements DataSource.SuccessCallBack<List<Category>>, DataSource.FailedCallBack {

  private CategoryRepository categoryRepository;
  private OnCategoryLoad load;
  private CompositeSubscription subscription;

  public CategoryPresenter(OnCategoryLoad load) {
    categoryRepository = new CategoryRepository();
    this.load = load;
    subscription = new CompositeSubscription();
  }

  public void loadData() {
    categoryRepository.load(this);
    Timber.e("网络请求--获取好友分组列表");
    subscription.add(
        UserHelper.getCategories().subscribe(new Subscriber<RspModel<List<CategoryCard>>>() {
          @Override public void onCompleted() {
            Timber.e("网络请求--获取好友分组列表---结束");
          }

          @Override public void onError(Throwable e) {
            Timber.e(e);
          }

          @Override public void onNext(RspModel<List<CategoryCard>> listRspModel) {
            if (listRspModel.isSuccess()) {
              List<CategoryCard> categoryCardList = listRspModel.getResult();
              if (categoryCardList == null || categoryCardList.size() == 0) return;
              Factory.getUserCenter().dispatchCategory(categoryCardList);
            } else {
              Factory.decodeRspCode(listRspModel, CategoryPresenter.this);
            }
          }
        }));
  }

  public void loadLocal() {
    categoryRepository.load(this);
  }

  public void destroy() {
    subscription.clear();
    categoryRepository.dispose();
  }

  @Override public void notifyData() {
    load.notifyCate();
  }

  @Override public void loadDataSuccess(List<Category> categories) {
    load.loadCategory(categories);
  }

  @Override public void loadDataFail(int strRes) {
    Timber.e(strRes + "----获取分组");
  }

  public interface OnCategoryLoad {
    void loadCategory(List<Category> categories);

    void notifyCate();
  }
}
